/*
 * @Author: your name
 * @Date: 2021-09-21 11:54:09
 * @LastEditTime: 2021-09-21 15:17:05
 * @LastEditors: Please set LastEditors
 * @Description: In User Settings Edit
 * @FilePath: \数据结构\栈\stack.c
 */

#include<stdio.h>
#include<stdlib.h>
#include<stdbool.h>
#include "stack.h"

bool isEmpty(STACK *s)
{
    return s->stackTop == EMPTY_POS;
}

bool isFull(STACK *s)
{
    return s->stackTop == s->capacity-1;
}

STACK* createStack(int stackSize)
{
    STACK *s;
    //判断stackSize的合法性
    if(stackSize <= 0){
        printf("stackSize Error\n");
        return NULL;
    }
    //申请栈内存
    s = (STACK*)malloc(sizeof(STACK));
    //申请栈空间失败
    if(!s){
        printf("no memory\n");
        return NULL;
    }
    //申请数组内存
    s->array = (elementType*)malloc(sizeof(elementType)*(stackSize+1));
    //失败
    if(!s->array){
        printf("no memory\n");
        return NULL;
    }
    //清空栈
    clearStack(s);
    s->capacity = stackSize;
    return s;
}

void freeStack(STACK *s)
{
    if(!s){
        if(!s->array){
            free(s->array);
        }
        free(s);
    }
}

elementType pop(STACK *s)
{
    //栈空,无法pop
    if(isEmpty(s)){
        printf("stack is empty, error\n");
        exit(-1);
    }
    return s->array[s->stackTop--];
}

bool push(STACK *s, elementType ele)
{
    //栈满,无法push
    if(isFull(s)){
        printf("stack is full, error\n");
        return false;
    }
    s->array[++s->stackTop] = ele;
    return true;
}

elementType top(STACK *s)
{
    if(isEmpty(s)){
        printf("stack is empty, error\n");
        exit(-1);
    }
    return s->array[s->stackTop];
}

bool clearStack(STACK *s)
{
    if(!s){
        printf("stack is invalid\n");
        return false;
    }
    s->stackTop = EMPTY_POS;
}